# coding=utf-8
import json
import traceback
from django.http import HttpResponse
from com.kjssoft.common.ant.files.upload import ProgressBarFileUploadHandler, ContentTypeCheckFileUploadHandler
from com.kjssoft.rainbow import LOGGER, RainbowViewServerException
from com.kjssoft.rainbow.consts import RainbowProfileConsts
from com.kjssoft.rainbow.models import PhotoModelServerException

__author__ = 'KJS'

class RainbowUserPermissionMiddleware(object):
    def process_request(self, request):
        if request.user and request.user.is_authenticated():
            #如果是登陆用户，检查用户是否有Rainbow的超级权限
            if request.user.groups.filter(name = RainbowProfileConsts.ADMIN_GROUP).count():
                LOGGER.debug('%s is rainbow admin.' % request.user)
                request.user.rainbow_admin = True
            else:
                LOGGER.debug('%s is not rainbow admin.' % request.user)
                request.user.rainbow_admin = False

class RainbowPhotoUploadMiddleware(object):

    def process_request(self, request):
        LOGGER.debug(request.get_full_path())
        #插入记录文件上传进度的处理器
        request.upload_handlers.insert(0, ProgressBarFileUploadHandler())
        #插入检查文件类型的处理器
        request.upload_handlers.insert(1, ContentTypeCheckFileUploadHandler())



class RainbowExceptionHandleMiddleware(object):
    def process_exception(self, request, exception):
        exc = traceback.format_exc()
        LOGGER.error('System exception %s, traceback %s' % (exception, exc))
        if isinstance(exception, PhotoModelServerException) or isinstance(exception, RainbowViewServerException):
            return HttpResponse(
                json.dumps({'errorCode':exception.code, 'description':exception.message}),
                mimetype = 'text/json'
            )
